package com.wxblockchain.core.utils;

import android.content.Context;
import android.os.Environment;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * Created by louyaming on 2020/04/21.
 */
public class FileUtil {

    public static final String POSTFIX = ".JPEG";
    public static final String POST_VIDEO = ".mp4";
    public static final String APP_NAME = "ImageSelector";
    public static final String CAMERA_PATH = "/" + APP_NAME + "/CameraImage/";
    public static final String CROP_PATH = "/" + APP_NAME + "/CropImage/";

    /**
     *  读取文件为byte数组
     *
     * @param filename
     * @return
     * @throws IOException
     */
    public static byte[] toByteArray(String filename) throws IOException {

        File f = new File(filename);
        if (!f.exists()) {
            throw new FileNotFoundException(filename);
        }

        ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length());
        BufferedInputStream in = null;
        try {
            in = new BufferedInputStream(new FileInputStream(f));
            int buf_size = 1024;
            byte[] buffer = new byte[buf_size];
            int len;
            while (-1 != (len = in.read(buffer, 0, buf_size))) {
                bos.write(buffer, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            bos.close();
        }
    }

    public static String getSdCardRootPath() {
        if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            LogUtil.e(FileUtil.class.getSimpleName(), "sd卡未加载");
            return "/";
        } else {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
    }

    /**
     * 从文件中读取所有字符串
     *
     * @param filePath
     * @return
     */
    public static String readFromFile(String filePath) {
        StringBuilder builder = new StringBuilder();
        InputStreamReader read = null;
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) {
                read = new InputStreamReader(
                        new FileInputStream(file));
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    builder.append(lineTxt);
                }
            } else {
                LogUtil.e(FileUtil.class.getSimpleName(), "找不到指定文件");
            }
        } catch (Exception e) {
            LogUtil.e(FileUtil.class.getSimpleName(), "读取文件内容出错");
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return builder.toString();
    }

    /**
     * 从assets中读取所有字符串
     *
     * @param filePath
     * @return
     */
    public static String readFromAssets(Context context, String filePath) {
        StringBuilder builder = new StringBuilder();
        InputStreamReader read = null;
        try {
            read = new InputStreamReader(
                    context.getAssets().open(filePath));
            BufferedReader bufferedReader = new BufferedReader(read);
            String lineTxt = null;
            while ((lineTxt = bufferedReader.readLine()) != null) {
                builder.append(lineTxt);
            }
        } catch (Exception e) {
            LogUtil.e(FileUtil.class.getSimpleName(), "读取文件内容出错");
            e.printStackTrace();
        } finally {
            if (read != null) {
                try {
                    read.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return builder.toString();
    }

    public static String getWebroot(Context context) {
        return context.getFilesDir().getAbsolutePath() + "/webroot";
    }

    public static String getSDCardWebroot(Context context) {
        File f = context.getExternalFilesDir("webroot");
        if (f != null) {
            return f.getAbsolutePath();
        } else {
            return "";
        }
    }

    public static File getPhotoCacheDir(Context context, File file) {
        File cacheDir = context.getCacheDir();
        if (cacheDir != null) {
            File mCacheDir = new File(cacheDir, "picture_cache");
            if (!mCacheDir.mkdirs() && (!mCacheDir.exists() || !mCacheDir.isDirectory())) {
                return file;
            } else {
                return new File(mCacheDir, file.getName());
            }
        }
        return file;
    }

    public static File createCameraFile(Context context, int type) {
        return createMediaFile(context, CAMERA_PATH, type);
    }

    public static File createCropFile(Context context, int type) {
        return createMediaFile(context, CROP_PATH, type);
    }

    private static File createMediaFile(Context context, String parentPath, int type) {
        String state = Environment.getExternalStorageState();
        File rootDir = state.equals(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory() : context.getCacheDir();

        File folderDir = new File(rootDir.getAbsolutePath() + parentPath);
        if (!folderDir.exists() && folderDir.mkdirs()) {

        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        String fileName = APP_NAME + "_" + timeStamp + "";
        File tmpFile = null;
        switch (type) {
            case 1:
                tmpFile = new File(folderDir, fileName + POSTFIX);
                break;
            case 2:
                tmpFile = new File(folderDir, fileName + POST_VIDEO);
                break;
        }
        return tmpFile;
    }

}
